<?php

App::uses('AppModel', 'Model');

class Invoice extends AppModel {
    
    public $order = 'Invoice.date DESC';
    
    public $belongsTo = array ('Campaign');
    
    public $validate = array(
        'campaign_id' => array(
            'rule'    => 'notEmpty',
            'message' => 'Morate odabrati kampanju.'
        ),
        'date' => array(
            'rule'    => 'notEmpty',
            'message' => 'Morate odabrati datum.'
        ),
        'date_valuta' => array(
            'rule'    => 'notEmpty',
            'message' => 'Morate odabrati datum valute.'
        ),
        'number'      => array(
            'rule'    => 'isUnique',
            'message' => 'Broj fakture već postoji.'
        )
    );
    
    public $hasOne = array(
        'ExchangeRate' => array(
            'className'  => 'CurrencyExchange',
            'foreignKey' => false,
            'conditions' => array('ExchangeRate.date <=' => 'Invoice.date'),
            'order'      => 'ExchangeRate.date DESC'
        )
    );
    
    public $hasMany = array(
        'InvoiceService' => array( 'dependent' => true )
    );
    
    public function afterFind($results, $primary=false) {
        if ($primary) {
            foreach ($results as &$invoice) {
                if (empty($invoice['Invoice']) || 
                    empty($invoice['Campaign']) ||
                    empty($invoice['ExchangeRate'])
                ) {
                    continue;
                }
                
                $campaignId = $invoice['Campaign']['id'];
                $Campaign = (object)$this->Campaign->findById($campaignId);
                
                $locations = $Campaign->CampaignsLocation;
                
                $CurrencyExchange = $this->ExchangeRate->find('first', array(
                    'conditions' => array('ExchangeRate.date <=' => $invoice['Invoice']['date']),
                    'order'      => 'ExchangeRate.date DESC'
                ));
                
                $exch_rate = (float)$CurrencyExchange['ExchangeRate']['rate'];
                $invoice['Invoice']['amount'] = 0;
                $locationTime = 0;
                foreach ($locations as $k=>$location) {
                    $l = array('CampaignsLocation' => $location);
                    $this->Campaign->CampaignsLocation->loadTax($l);
                    $invoice['Campaign']['Location'][$k]['Tax'] = $l['Tax'];
                    $tax  = (float)$l['Tax']['value']/100;

                    // need to recalculate the price
                    $data = array(
                        'Location'          => $Campaign->Location[$k],
                        'CampaignsLocation' => $location
                    );
                    
                    $end   = $invoice['Invoice']['date'];
                    $start = date('Y-m-01', strtotime($end));
                    if (strtotime($start) < strtotime($location['start'])) {
                        $start = $location['start'];
                    }
                    $price = $this->Campaign->CampaignsLocation->calculatePrice($data, $start, $end);
                    $sum = $price->rent +
                           $price->production +
                           $price->mount;
                    
                    $invoice['Invoice']['amount'] += $sum * $exch_rate * (1+$tax);
                    
                    // copy tax to Campaign
                    $t = strtotime($location['start']);
                    if ($t < $locationTime || $locationTime==0) {
                        $locationTime = $t;
                        $invoice['Campaign']['Tax'] = $l['Tax'];
                    }
                }
            }
        }
        
        return $results;
    }
    
    public function getNextId() {
        $last = (int)$this->find('first', array(
            'fields' => 'Invoice.id',
            'order'  => 'Invoice.id DESC'
        ));
        return $last+1;
    }
    
    public function create($data=null, $filterKey=false) {
        if (empty($data)) {
            $id = $this->getNextId();
            $data = array(
                'number' => sprintf("%04d/%d", $id, date('y')),
                'title'  => 'Račun'
            );
        }
        
        return parent::create($data, $filterKey);
    }

    public function deleteRelatedData() {
        if ($this->id) {
            $this->InvoiceService->deleteAll(array('InvoiceService.invoice_id' => $this->id));
        }
    }
    
    public function getClientInvoices($clientId, $start, $end) {
        $invoices = $this->find('all', array(
            'fields' => array('Invoice.*', 'Campaign.*', 'ExchangeRate.*'),
            'conditions' => array(
                'Invoice.date >='    => $start,
                'Invoice.date <='    => $end,
                'Invoice.storno !='  => 1,
                'Campaign.client_id' => $clientId
            ),
            'recursive' => 0
        ));
        
        return $invoices;
    }
    
}

?>
